package com.weds.data_sync.interceptor;

import com.weds.data_sync.constant.BizCodeEnum;
import com.weds.data_sync.pojo.LoginUser;
import com.weds.data_sync.util.CommonUtil;
import com.weds.data_sync.util.JsonData;
import com.weds.data_sync.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Description 登录拦截器
 * @Author lihw
 * @Date 2024/1/4 14:13
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 前后端分离时，前端通过这个方法刺探后台服务是否正常
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }

        String token = request.getHeader("Authentication");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("Authentication");
        }

        if (StringUtils.isNotBlank(token)) {
            Claims claims = JwtUtil.parseToken(token);

            if (Objects.isNull(claims)) {
                // 未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }

            long userId = Long.parseLong(claims.get("userId").toString());
            String username = claims.get("username").toString();

            LoginUser loginUser = LoginUser.builder()
                    .id(userId)
                    .username(username)
                    .build();

            threadLocal.set(loginUser);
            return true;
        }

        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));

        return false;
    }
}
